<template>
    <el-dialog title="" :visible.sync="dialogStartProcessVisibleInChild" :fullscreen="false" >
        <div slot="title">
            <div class="formTitle">
                <img :src="headerInfo.companyLogoSrc" />
                <span class="tit">{{headerInfo.companyName}}</span>
            </div>
        </div>
        <!-- <div v-if="generateStartFormVisible&&startFormJson.list">
            <fm-generate-form :data="startFormJson" ref="generateStartForm">
            </fm-generate-form>
        </div> -->
        <div v-if="generateStartFormVisible&&startFormJson.column">
            <avue-form 
                   ref="form"
                   class="generate-form"
                   :option="startFormJson"
                   v-model="widgetModels"
                   @submit="handlePreviewSubmit">
                   <template slot="staticAppUser" slot-scope="scope">
                        <div>
                           <el-input @click="showPropScope(scope)" disabled v-model="widgetModels.staticAppUser" />
                           <el-input v-show="false" v-model="widgetModels.staticAppUserId" />
                        </div>
                    </template>
                    <template slot="staticAgentUser">
                        <div>
                           <el-input disabled v-model="widgetModels.staticAgentUser" />
                           <el-input v-show="false" v-model="widgetModels.staticAgentUserId" />
                        </div>
                    </template>
                    <template slot="staticUserDept">
                        <div>
                           <el-input disabled v-model="widgetModels.staticUserDept" />
                           <el-input v-show="false"  v-model="widgetModels.staticUserDeptId" />
                        </div>
                    </template>
                    <template slot="staticAgentUserDept">
                        <div>
                           <el-input disabled v-model="widgetModels.staticAgentUserDept" />
                           <el-input v-show="false" v-model="widgetModels.staticAgentUserDeptId" />
                        </div>
                    </template>
            </avue-form>
        </div>
        <select-user ref="selectUser" :visible.sync="selectUserVisible" :appendToBody="true"
                     :multipleSelect="true"
                     @selectUserFinished="selectUserFinished"></select-user>
        <div slot="footer" class="dialog-footer">
            <el-form label-width="100px">
                <el-form-item label="业务主键Key:" v-if="showBusinessKey">
                    <el-input v-model="businessKey" placeholder="请输入业务主键Key"/>
                </el-form-item>
                <el-form-item label="抄送给:">
                    <el-row align="left">
                        <el-col :span="6" align="left">
                            <autoCompleteUserName 
                               v-model = 'autoVal'
                               @handleSelect="autoCompleteUserNameSelect"
                            ></autoCompleteUserName>
                        </el-col>
                        <el-col :span="1" align="left">
                            <i class="el-icon-plus el-icon--left" style="cursor:pointer" @click="doSelectCcTo"></i>
                        </el-col>
                        <el-col :span="13" align="left">
                            <el-tag v-for="tag in ccToVos" :key="tag.userId" effect="plain" closable
                                    @close="handleCcToClose(tag)"
                                    style="margin-left: 5px">{{tag.realName}}
                            </el-tag>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="选择部门:" required>
                    <el-row align="left">
                        <el-col :span="18" align="left">
                            <el-select v-model="deptId" @change="deptSelectChange" placeholder="请选择">
                                <el-option
                                v-for="item in deptOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>
            <el-button icon="el-icon-close" @click="dialogStartProcessVisibleInChild = false">取消</el-button>
            <!-- <el-button icon="el-icon-check" type="primary" @click="doStartInstance">确定
            </el-button> -->
            <el-button icon="el-icon-document" type="primary" @click="saveDraft">存为草稿
            </el-button>
            <el-button icon="el-icon-tickets" type="primary" @click="saveTemplate">存为范本
            </el-button>
            <el-button icon="el-icon-check" type="primary" @click="doStartInstanceSubmit">确定
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {getAction, postAction} from '@/api/manage'
    import {Message} from 'element-ui'
    import {mapGetters} from "vuex"
    import SelectUser from '@/components/select/SelectUser'
    import autoCompleteUserName from '@/components/select/autoCompleteUserName'
    export default {
        name: 'StartProcess',
        components: {SelectUser,autoCompleteUserName},
        props: {
            visible: {
                type: Boolean,
                default: function () {
                    return false
                }
            },
            processDefinition: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            ownerUserId: {
                type: String,
                default:''
            },
            curStartProcess: {
                type: Object,
                default: function () {
                    return {}
                }
            },
        },
        computed: {
            ...mapGetters(["userInfo"]),
            dialogStartProcessVisibleInChild: {
                get() {
                    return this.visible
                },
                set(val) {
                    this.$emit('update:visible', val)
                }
            }
        },
        data() {
            return {
                // fullscreen: true,
                autoVal:'',
                generateStartFormVisible: false,
                startFormJson: undefined,
                variables: undefined,
                showBusinessKey: false,
                businessKey: undefined,
                selectUserVisible: false,
                ccToVos: [],
                headerInfo:{
                    companyName:'',
                    companyLogoSrc:''
                },
                widgetModels: {},
                deptOptions: [],
                deptId:'',
                submitType:'usu',  //提交类型： 正常提交-usu  草稿提交-draft 范本提交-template
                draftId:'',
                agentSelectUser:{},
                appType:'usu'  //申请类型， usu-常规，agent-代填
            }
        },
        created() {
            this.initData()
            this.getHeaderInfo()
            this.initDeptOptions()
        },
        methods: {
            showPropScope(scope){
                console.log(scope,'scope>>')
            },
            initData() {
                debugger
                if (this.processDefinition.formKey) {
                    getAction('/api/sdt-flow/flowable/processDefinition/renderedStartForm', {processDefinitionId: this.processDefinition.id}).then(res => {
                        const data = res.data.data
                        this.showBusinessKey = data.showBusinessKey
                        if (data.renderedStartForm) {
                            this.startFormJson = JSON.parse(data.renderedStartForm)
                            this.generateStartFormVisible = true
                            this.fieldInit()
                        }
                    })
                }else if(this.processDefinition.key){
                    getAction('/api/sdt-flow/flowable/processDefinition/renderedStartForm-collect', {processDefinitionKey: this.processDefinition.key}).then(res => {
                        const data = res.data.data
                        this.showBusinessKey = data.showBusinessKey
                        if (data.renderedStartForm) {
                            this.startFormJson = JSON.parse(data.renderedStartForm)
                            this.generateStartFormVisible = true
                            this.fieldInit()
                        }
                    })
                }
                // else {
                //     this.fullscreen = false
                // }
            },
            fieldInit(){
                // deptId: "1318111073490788353,1326367863370158081"
                // deptName: "信息管理部,系统开发组队"
                if(this.appType == 'agent'){
                    //debugger
                   this.widgetModels.staticAppUser = this.agentSelectUser.userName
                   this.widgetModels.staticAppUserId = this.agentSelectUser.userId
                   let {userName,account,deptId,deptName} = this.userInfo
                   this.widgetModels.staticAgentUser = userName
                   this.widgetModels.staticAgentUserId = account
                   this.widgetModels.staticAgentUserDept = deptName?deptName.split(',')[0]:''
                   this.widgetModels.staticAgentUserDeptId = deptId?deptId.split(',')[0]:''
                   //debugger
                }else{
                   let {userName,account} = this.userInfo
                   this.widgetModels.staticAppUser = userName
                   this.widgetModels.staticAppUserId = account
                }
                
                
            },
            getHeaderInfo(){
                getAction('/api/blade-system/dict/dictionary?code=form_head').then(res=>{
                     //debugger
                     let data = res.data.data
                     this.headerInfo = {
                         companyName : data[2].remark,
                         companyLogoSrc : data[1].remark,
                     }
                })
            },
            initDeptOptions(userId=null){
                let params = null
                if(userId){
                   params = {
                     userId
                   }
                }

                getAction('/api/sdt-flow/flowable/processInstance/get-user-depts',params).then(res=>{
                     // deptId: 1123598813738675200,deptName: "刀锋科技",fullDeptName: "//刀锋科技",parentId: 0
                     let data = res.data.data.map(ele => {
                          return {
                               value: ele.deptId,
                               label: ele.fullDeptName
                          }
                     })
                    //  debugger
                    //  data.push({
                    //      value: 'testttid',
                    //      label: '测试部门'
                    //  })
                    //  data.push({
                    //      value: 'testttid22',
                    //      label: '测试部门2'
                    //  })
                     this.deptOptions = data
                     console.log(this.deptOptions,'this.deptOptions------------------------------》')
                     if(this.deptOptions.length>0){
                         let defaultDept = this.deptOptions[0]
                         this.deptId = defaultDept.value
                         this.widgetModels.staticUserDept = defaultDept.label
                         this.widgetModels.staticUserDeptId = defaultDept.value
                     }
                     
                })
            },
            doStartInstance() { 
                let self = this
               
                if (this.$refs.generateStartForm) {
                    this.$refs.generateStartForm.getData().then(values => {
                        
                        if (values && values != undefined) {
                            let processInstanceFormData = JSON.stringify(values)
                            let realValues = Object.assign({processInstanceFormData}, values)
                            let params = {
                                processDefinitionId: this.processDefinition.id,
                                businessKey: this.businessKey,
                                values: realValues,
                                ccToVos: this.ccToVos
                            }
                            if(self.ownerUserId){
                                params.isAgent = true
                                params.ownerUserId = self.ownerUserId
                            }
                            return postAction('/api/sdt-flow/flowable/processInstance/start', params).then((res) => {
                                Message.success(res.data.msg)
                                this.dialogStartProcessVisibleInChild = false
                                //this.$emit('end')
                            })
                        }
                    }).catch(e => {
                    })
                } else {
                    postAction('/api/sdt-flow/flowable/processInstance/start', {
                        processDefinitionId: this.processDefinition.id,
                        businessKey: this.businessKey,
                        ccToVos: this.ccToVos
                    }).then((res) => {
                        Message.success(res.data.msg)
                        this.dialogStartProcessVisibleInChild = false
                        //this.$emit('end')
                    })
                }
            },
            doStartInstanceSubmit() { 
                let self = this
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        if(!this.deptId){
                            this.$message.error('请选择部门')
                            return
                        }
                        let values = this.widgetModels
                        values.userTest = {name:'tom',id:'324234234'}
                        if (values && values != undefined) {
                            let processInstanceFormData = JSON.stringify(this.widgetModels)
                            let realValues = Object.assign({processInstanceFormData}, values)
                            let params = {
                                processDefinitionId: this.processDefinition.id,
                                businessKey: this.businessKey,
                                values: realValues,
                                ccToVos: this.ccToVos,
                                deptId:this.deptId
                            }
                            debugger
                            //return
                            if(self.ownerUserId){
                                params.isAgent = true
                                params.ownerUserId = self.ownerUserId
                            }
                            if(this.submitType=='draft'){
                                params.draftId = this.draftId
                            }
                            return postAction('/api/sdt-flow/flowable/processInstance/start', params).then((res) => {
                                Message.success(res.data.msg)
                                this.dialogStartProcessVisibleInChild = false
                                this.submitType=='usu'
                                this.draftId = ''
                                //this.$emit('end')
                            })
                        }
                    } else {
                        this.$message.error('缺少必填字段，请填写完整')
                        return false;
                    }
                });
                
                
                 
            },
            saveDraft(){

                this.$prompt('请输入草稿名称(非必填)', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(({ value }) => {
                        let draftName = value
                        console.log(this.curStartProcess)
                        let curStartProcess = this.curStartProcess
                        let self = this
                        let values = this.widgetModels
                        let data = {
                            draftName:draftName?draftName:'',
                            formData:values,
                            dataType:'draft',
                            procDefId:curStartProcess.procDefId,
                            procDefKey:curStartProcess.procDefKey,
                            procDefName: curStartProcess.procDefName,
                        }
                        postAction('/api/sdt-flow/flowable/form/save-draft', data).then((res) => {
                                Message.success(res.data.msg)
                                this.dialogStartProcessVisibleInChild = false
                                //this.$emit('end')
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消'
                        });       
                });
                
            },
            saveTemplate(){

                this.$prompt('请输入范本名称(非必填)', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(({ value }) => {
                        let draftName = value
                        console.log(this.curStartProcess)
                        let curStartProcess = this.curStartProcess
                        let self = this
                        let values = this.widgetModels
                        let data = {
                            draftName:draftName?draftName:'',
                            formData:values,
                            dataType:'template',
                            procDefId:curStartProcess.procDefId,
                            procDefKey:curStartProcess.procDefKey,
                            procDefName: curStartProcess.procDefName,
                        }
                        postAction('/api/sdt-flow/flowable/form/save-draft', data).then((res) => {
                                Message.success(res.data.msg)
                                this.dialogStartProcessVisibleInChild = false
                                //this.$emit('end')
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消'
                        });       
                });
                
            },
            useDraft(data){
                let formData = data.formData
                this.widgetModels = formData
                this.submitType = 'draft'
                this.draftId = data.id
            },
            useTemplate(data){
                let formData = data.formData
                this.widgetModels = formData
            },
            selectUserFinished(selectData) {
                if (!selectData || selectData.length == 0) {
                    Message.error('请先选择用户')
                    return
                }
                //debugger
                //this.ccToVos = selectData
                this.pushCcToVos(selectData)
            },
            pushCcToVos(data){
               data.forEach(ele => {
                   if(this.ccToVos.every(item => {
                        return item.account!=ele.account
                   })){
                       this.ccToVos.push(ele)
                   }
               })
            },
            handleCcToClose(tag) {
                this.ccToVos.splice(this.ccToVos.indexOf(tag), 1);
            },
            doSelectCcTo() {
                this.selectUserVisible = true
                if (this.$refs.selectUser.treeData.length == 0) {
                    this.$refs.selectUser.getTreeData()
                }
            },
            autoCompleteUserNameSelect(selection){
                
                this.pushCcToVos([selection])
            },
            selectPeople(){
                alert(12)
                this.widgetModels.staticAppUserName = '林晓锋'
                this.widgetModels.staticAppUserId = 'sdt13841'
                console.log(this.widgetModels,'this.widgetModels')
            },
            initAgentApplication(user){
                debugger
                this.agentSelectUser = user
                this.appType = 'agent'
                setTimeout(()=>{
                     this.initDeptOptions(user.userId)
                },1000)
               
                // if(this.formPropGet('staticAppUser')){
                //     this.widgetModels.staticAppUser = user.userId
                // }
            },
            formPropGet(prop){
                return this.widgetModels[prop]
            },
            //选择部分时更新申请人部门
            deptSelectChange(val){
                let value = val
                let selectionItem = this.deptOptions.filter(item => {
                    return item.value == value
                })[0]
                let label = selectionItem.label
                this.widgetModels.staticUserDept = label
                this.widgetModels.staticUserDeptId = value
                // debugger
            }
        }
    }
</script>

<style lang="scss" scoped>
  .formTitle{
      height: 48px;
      line-height: 30px;
      text-align: center;
      position: relative;
      border-bottom: 1px solid #d7dfe6;
      zoom: 0;
      overflow: hidden;
      img{
         height: 40px;
         float:left;
      }
      .tit{
         display:inline-block;
         height: 40px;
         line-height: 40px;
         width: 100%;
         position: absolute;
         top: 0;
         left: 0;
         font-size: 23px;
         color: #8c8c8c;
      }
  }
  .dialogTitle{
      margin-top: -20px;
      font-size: 18px;
      line-height: 61px;
      margin-bottom: 30px;
      text-align: center;
  }
</style>